﻿using Microsoft.Extensions.Caching.Memory;

namespace KAs.Cache;

public class MemoryCache : ICache
{
    private readonly IMemoryCache _cache;

    public MemoryCache(IMemoryCache cache)
    {
        _cache = cache;
    }

    public T Get<T>(string key)
    {
        return _cache.Get<T>(key);
    }
    public async Task<string?> GetAsync(string key)
    {
        return _cache.Get(key)?.ToString();
    }
    public async Task<T> GetAsync<T>(string key)
    {
        return _cache.Get<T>(key);
    }

    public async Task<T> GetOrAddAsync<T>(string key, Func<Task<T>> func, TimeSpan expiredSeconds)
    {
        var cacheValue = _cache.Get<T>(key);
        if (cacheValue != null)
        {
            return cacheValue;
        }
        else
        {
            var value = await func.Invoke();
            if (value != null)
            {
                _cache.Set(key, value, expiredSeconds);
            }

            return value;
        }
    }
    public void Remove(string key)
    {


        _cache.Remove(key);
    }
    public async Task RemoveAsync(string key)
    {


        _cache.Remove(key);
    }
    public void Set(string key, object value)
    {
        _cache.Set(key, value);
    }
    public void Set(string key, object value, TimeSpan timeSpan)
    {
        _cache.Set(key, value, timeSpan);
    }
    public async Task SetAsync(string key, string value)
    {
        await SetAsync(key, value, TimeSpan.FromSeconds(7200));
    }
    public async Task SetAsync(string key, string value, TimeSpan timeSpan)
    {
        _cache.Set(key, value);
    }
    public async Task SetAsync(string key, object value)
    {
        _cache.Set(key, value);
    }
    public async Task SetAsync(string key, object value, TimeSpan timeSpan)
    {
        _cache.Set(key, value, timeSpan);
    }
    public async Task<double> StringIncrementAsync(string key, double count)
    {
        throw new NotImplementedException();
    }
    public async Task<int> StringIncrementAsync(string key, int count)
    {
        var total = Get<int>(key);
        total += count;
        _cache.Set(key, total);
        return total;
    }

    public async Task<double> StringDecrementAsync(string key, double count)
    {
        throw new NotImplementedException();
    }

    public void Refresh(string key, TimeSpan timeSpan)
    {
        var value = _cache.Get(key);
        if (value != null)
            _cache.Set(key, value, timeSpan);
    }

    public async Task RefreshAsync(string key, TimeSpan timeSpan)
    {
        var value = _cache.Get(key);
        if (value != null)
            _cache.Set(key, value, timeSpan);
    }
}
